<template>
  <view class="container">
    <!-- 视频显示区域 -->
    <video
      ref="video"
      id="video"
      :src="videoSrc"
      :poster="videoPoster"
      :style="{ background: videoBackground }"
      controls
    ></video>

    <!-- 控制按钮 -->
    <button tap="presenter" :disabled="isPresenterDisabled">成为主讲人</button>
    <button tap="viewer" :disabled="isViewerDisabled">成为观众</button>
    <button tap="stop" :disabled="isStopDisabled">停止</button>
    <!-- 聊天输入框 -->
    <input v-model="chatInput" placeholder="输入聊天内容" />
    <button tap="sendChat">发送</button>

    <!-- 注册输入框 -->
    <input v-model="registerName" placeholder="输入用户名" />
    <button @cltapick="register" :disabled="isRegisterDisabled">注册</button>
	<button @tap="comback">返回</button>
	
  </view>
</template>

<script>
import kurentoUtils from 'kurento-utils'; // 确保 kurento-utils 已安装

export default {
  data() {
    return {
      ws: null, // WebSocket 实例
      videoSrc: '', // 视频源
      videoPoster: '/static/webrtc.png', // 视频封面
      videoBackground: '', // 视频背景（用于加载动画）
      webRtcPeer: null, // WebRTC 实例
      chatInput: '', // 聊天输入内容
      registerName: '', // 注册用户名
      isPresenterDisabled: false, // 主讲人按钮是否禁用
      isViewerDisabled: false, // 观众按钮是否禁用
      isStopDisabled: true, // 停止按钮是否禁用
      isRegisterDisabled: false, // 注册按钮是否禁用
      registerState: 0, // 注册状态：0-未注册，1-注册中，2-已注册
    };
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    // 初始化 WebSocket
    initWebSocket() {
      this.ws = uni.connectSocket({
        url: `wss://${location.host}/call`,
      });

      this.ws.onMessage((message) => {
        const parsedMessage = JSON.parse(message.data);
        console.info('Received message:', parsedMessage);

        switch (parsedMessage.id) {
          case 'presenterResponse':
            this.presenterResponse(parsedMessage);
            break;
          case 'viewerResponse':
            this.viewerResponse(parsedMessage);
            break;
          case 'iceCandidate':
            this.webRtcPeer.addIceCandidate(parsedMessage.candidate, (error) => {
              if (error) console.error('Error adding candidate:', error);
            });
            break;
          case 'stopCommunication':
            this.dispose();
            break;
          case 'chatResponse':
            this.chatResponse(parsedMessage);
            break;
          case 'registerResponse':
            this.setRegisterState(2); // 注册成功
            break;
          default:
            console.error('Unrecognized message:', parsedMessage);
        }
      });
    },

    // 发送消息
    sendMessage(message) {
      const jsonMessage = JSON.stringify(message);
      console.log('Sending message:', jsonMessage);
      this.ws.send({
        data: jsonMessage,
      });
    },

    // 主讲人模式
    presenter() {
      if (!this.webRtcPeer) {
        this.showSpinner();
        const options = {
          localVideo: this.$refs.video,
          onicecandidate: this.onIceCandidate,
        };
        this.webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options, (error) => {
          if (error) return console.error(error);
          this.webRtcPeer.generateOffer(this.onOfferPresenter);
        });
        this.enableStopButton();
      }
    },

    // 观众模式
    viewer() {
      if (!this.webRtcPeer) {
        this.showSpinner();
        const options = {
          remoteVideo: this.$refs.video,
          onicecandidate: this.onIceCandidate,
        };
        this.webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options, (error) => {
          if (error) return console.error(error);
          this.webRtcPeer.generateOffer(this.onOfferViewer);
        });
        this.enableStopButton();
      }
    },

    // 停止
    stop() {
      this.sendMessage({ id: 'stop' });
      this.dispose();
    },

    // 释放资源
    dispose() {
      if (this.webRtcPeer) {
        this.webRtcPeer.dispose();
        this.webRtcPeer = null;
      }
      this.hideSpinner();
      this.disableStopButton();
    },

    // 显示加载动画
    showSpinner() {
      this.videoBackground = 'center transparent url("/static/spinner.gif") no-repeat';
    },

    // 隐藏加载动画
    hideSpinner() {
      this.videoBackground = '';
    },

    // 启用停止按钮
    enableStopButton() {
      this.isPresenterDisabled = true;
      this.isViewerDisabled = true;
      this.isStopDisabled = false;
    },

    // 禁用停止按钮
    disableStopButton() {
      this.isPresenterDisabled = false;
      this.isViewerDisabled = false;
      this.isStopDisabled = true;
    },

    // 发送聊天消息
    sendChat() {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      const message = {
        id: 'chat',
        data: this.chatInput,
        role: 'viewer',
        token: token,
      };
      this.sendMessage(message);
      this.chatInput = ''; // 清空输入框
    },
	//返回上层
	comback() {
		uni.switchTab({
			url: '/pages/tabBars/mine'
		})
				//如果开播状态
				// if (!this.isStarPusher) {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '确定结束直播吗',
				// 		success: res => {
				// 			if (res.confirm) {
				// 				this.stopLive()
				// 			} else if (res.cancel) {
				// 				console.log('用户点击取消');
				// 			}
				// 		}
				// 	});
				// } else {
				// 	uni.switchTab({
				// 		url: '/pages/tabBars/mine'
				// 	})
				// }
			},
		//结束直播
		stopLive() {
			this.context.stop({
				success: a => {
					this.isEndPusher = true
					this.isStarPusher = true
					console.log(JSON.stringify(a));
				}
			});
		},
    // 注册
    register() {
      if (!this.registerName) {
        uni.showToast({ title: '请输入用户名', icon: 'none' });
        return;
      }
      this.setRegisterState(1); // 注册中
      this.sendMessage({
        id: 'register',
        name: this.registerName,
      });
    },

    // 设置注册状态
    setRegisterState(state) {
      this.registerState = state;
      this.isRegisterDisabled = state !== 0;
    },
  },
};
</script>

<style>
.container {
  padding: 20px;
}
video {
  width: 100%;
  height: 300px;
  background-color: #000;
}
button {
  margin: 10px 0;
}
</style>